<template>
  <div class="basic-wrap">
    <div class="button-wrap">
      <a-space>
        <a-button type="primary" @click="open = true">上传</a-button>
        <a-button>导出</a-button>
      </a-space>
    </div>
    <div class="table-wrap">
      <a-table size="middle" :dataSource="dataSource" :columns="columns">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'operation'">
            <a-button
              class="button-interval"
              type="link"
              size="small"
              @click="handleShowFile(record)"
            >
              查看
            </a-button>
            <a-button
              class="button-interval"
              type="link"
              size="small"
              @click="handleSetting(record)"
            >
              下载
            </a-button>
            <a-button
              class="button-interval"
              type="link"
              size="small"
              @click="handleSetting(record)"
            >
              文字识别
            </a-button>
            <a-button
              class="button-interval"
              type="link"
              size="small"
              @click="handleDeleteUser(record)"
            >
              删除
            </a-button>
          </template>
        </template>
      </a-table>
    </div>
    <a-modal v-model:visible="open" title="上传资料" @ok="handleAddSubmit">
      <a-form
        ref="formRef"
        style="margin-top: 24px"
        :model="formState"
        name="basic"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 17 }"
        autocomplete="off"
      >
        <a-form-item
          label="合同名称"
          name="contractName"
          :rules="[
            { required: true, message: 'Please input your contractName!' },
          ]"
        >
          <a-input
            readOnly
            onfocus="this.removeAttribute('readonly');"
            onblur="this.setAttribute('readonly',true);"
            v-model:value="formState.contractName"
          />
        </a-form-item>
        <a-form-item label="资料时间" name="contractTime">
          <a-date-picker v-model:value="dateValue" />
        </a-form-item>
        <a-form-item
          label="所属用户"
          name="userId"
          :rules="[{ required: true, message: 'Please input your userId!' }]"
        >
          <a-input
            readOnly
            onfocus="this.removeAttribute('readonly');"
            onblur="this.setAttribute('readonly',true);"
            v-model:value="formState.userId"
          />
        </a-form-item>
      </a-form>
      <div style="margin-left: 24px; margin-right: 24px">
        <a-upload-dragger
          v-model:fileList="fileList"
          name="file"
          :multiple="true"
          action="/api/contract/uploadFile"
          :headers="{
            authorization: 'Bearer ' + accessStore.accessToken,
          }"
          @change="handleChange"
        >
          <p class="ant-upload-drag-icon">
            <inbox-outlined></inbox-outlined>
          </p>
          <p class="ant-upload-text">
            Click or drag file to this area to upload
          </p>
          <p class="ant-upload-hint">
            Support for a single or bulk upload. Strictly prohibit from
            uploading company data or other band files
          </p>
        </a-upload-dragger>
      </div>
    </a-modal>
    <a-modal v-model:visible="openFiles" title="查看资料" width="68%">
      <FileList :id="currentContractId" :key="refreshKey"></FileList>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, unref, computed, onMounted, reactive, watch } from 'vue';
import type { FormInstance } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import type { Dayjs } from 'dayjs';
import type { ContractSo, ContractPageVo, ContractFileDto } from '#/api/common';
import dayjs from 'dayjs';
import { pageContractApi, uploadContractApi } from '#/api';
import { useAccessStore } from '@vben/stores';
import FileList from './fileList.vue';
const keyword = ref<string>('');
const refreshKey = ref<string>('');
const dataSource = ref<ContractPageVo[]>([]);
type RangeValue = [Dayjs, Dayjs];
const searchDate = ref<RangeValue>();
const dateValue = ref<Dayjs>();
const loading = ref(false);
const open = ref(false);
const openFiles = ref(false);
const formRef = ref<FormInstance>();
const fileList = ref([]);

const accessStore = useAccessStore();

let fileListData = ref<ContractFileDto[]>([]);
let currentContractId = ref<string>('');

const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 10,
  size: '',
  showSizeChanger: false,
  showQuickJumper: false,
});
const pageParam = computed(() => ({
  query: {
    keyword: unref<string>(keyword),
    contractStartTime: searchDate.value?.[0]
      ? dayjs(searchDate.value?.[0]).format('YYYY-MM-DD')
      : null,
    contractEndTime: searchDate.value?.[1]
      ? dayjs(searchDate.value?.[1]).format('YYYY-MM-DD')
      : null,
    uploadStartTime: undefined,
    uploadEndTime: undefined,
    clienteleId: undefined,
  },
  current: pagination.value?.current,
  size: pagination.value?.pageSize,
}));

let formState = reactive<ContractApi.ContractBo>({
  contractName: '',
  contractDate: '',
  userId: '',
  files: [],
});

// const dataSource = [
//   {
//     id: '123123123',
//     contractName: '关于XXX的研究报告',
//     contractDate: '2024-10-23',
//     clienteleName: '浙江交通科学研究院大数据中心有限公司',
//     createTime: '2024-10-23 00:00:00',
//   },
//   {
//     id: '123123124',
//     contractName: '关于XXX的研究报告',
//     contractDate: '2024-10-23',
//     clienteleName: '浙江交通科学研究院大数据中心有限公司',
//     createTime: '2024-10-23 00:00:00',
//   },
// ];
const columns = [
  {
    title: '合同名称',
    dataIndex: 'contractName',
    key: 'contractName',
    align: 'center',
  },

  {
    title: '合同日期',
    dataIndex: 'contractDate',
    key: 'contractDate',
    width: 160,
    align: 'center',
  },
  {
    title: '合同所属用户',
    dataIndex: 'ownUserName',
    key: 'ownUserName',
    width: 400,
    align: 'center',
  },
  {
    title: '上传时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 200,
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    width: 250,
    align: 'center',
  },
];

onMounted(() => {
  list();
});

watch(dateValue, (newValue, oldValue) => {
  console.log(`新值: ${newValue}, 旧值: ${oldValue}`);
  formState.contractDate = dayjs(newValue).format('YYYY-MM-DD');
});

async function list() {
  loading.value = true;
  const res = await pageContractApi(unref(pageParam));
  dataSource.value = res.records;
  pagination.value.total = Number(res.total);
  pagination.value.current = Number(res.current);
  loading.value = false;
}

const handleAddSubmit = () => {
  formRef.value
    ?.validateFields()
    .then(() => {
      // formState.files = fileResultList.value;
      // console.log('fileResultList', fileResultList);
      console.log('formState', formState);
      uploadContractApi(formState).then(() => {
        message.success('上传成功');
      });
      // addUser(formState).then(() => {
      //   message.success('添加成功')
      //   open.value = false
      //   list()
      // })
    })
    .catch((e) => {
      console.log('表单错误', e);
      message.error('表单填写错误');
    });
};
const handleChange = (info: UploadChangeParam) => {
  console.log('handleChange info', info);
  if (info.file.status !== 'uploading') {
    console.log(info.file, info.fileList);
  }
  if (info.file.status === 'done') {
    message.success(`${info.file.name} file uploaded successfully`);
    console.log(info.file.response.data);
    formState.files.push(info.file.response.data);
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} file upload failed.`);
  }
};

const handleShowFile = (record) => {
  refreshKey.value = Math.random();
  currentContractId.value = record.id;
  openFiles.value = true;
};
</script>
<style lang="less">
.basic-wrap {
  margin: 0 16px;
}
.button-wrap {
  margin: 16px 0;
}
</style>
